﻿function WrapTextBox(textBoxId, hiddenFieldId, sourceUrl)
{
	var textBoxIdSelector = "#" + textBoxId;
	var hiddenFieldSelector = "#" + hiddenFieldId;

	$(textBoxIdSelector).autocomplete(
	{
		source: function (request, response)
		{
			$.ajax(
			{
				url: sourceUrl,
				dataType: "json",
				minLength: 0,
				data:
				{
					featureClass: "P",
					style: "full",
					maxRows: 12,
					name_contains: request.term
				},
				success: function (data)
				{
					response($.map(data, function (item)
					{
						var text = item.Text;
						return {
							label: "<span class='autocompleteItem'>" + text.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<span class='autocomplete'>$1</span>") + "</span>",
							value: item.Text,
							id: item.Value,
							FullName: item.FullName ? item.FullName : undefined
						};
					}));
				}
			})
		},
		minLength: 0,
		select: function (event, ui)
		{
			$(hiddenFieldSelector).val(ui.item.id);

			if (ui.item.FullName)
			{
				$(textBoxIdSelector).val(ui.item.FullName);
			}
			else
				$(textBoxId).val(ui.item.value);
			return false;
		},
		change: function (event, ui)
		{
		},
		open: function ()
		{
			$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
		},
		close: function ()
		{
			$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
		}
	});
}